package org.jeecg.lawcase.data.reader.impl;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.lawcase.data.reader.DataImportApadter;
import org.jeecg.lawcase.data.reader.DataImportManager;
import org.jeecg.lawcase.data.reader.DataTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Component
public class TextDataImportImpl implements DataImportApadter {

    public TextDataImportImpl() {
        DataImportManager.registerService(this.getFileType(), this);
    }

    private DataTemplate dataTemplate = new DataTemplate();

    @Override
    public String getFileType() {
        return "txt";
    }

    @Override
    public DataTemplate importData(String fileName, InputStream inputStream) {
        String line = null;
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
            while (StringUtils.isNotBlank(line = br.readLine())) {
                // 按行读取数据
                if(dataTemplate.getHeaders().size() == 0){
                    this.setHeader(dataTemplate, line);
                } else {
                    this.addRow(dataTemplate, line);
                }
            }
        } catch (Exception e){
            throw new JeecgBootException(e);
        }
        return dataTemplate;
    }

    /**
     * 读取文件头
     * @param dataTemplate
     * @param line
     */
    public void setHeader(DataTemplate dataTemplate, String line){
        String[] titles = line.split("\t");
        for(String title: titles){
            dataTemplate.getHeaders().add(title);
        }
    }

    /**
     * 读取数据内容
     * @param dataTemplate
     * @param line
     */
    public void addRow(DataTemplate dataTemplate, String line){
        String[] datas = line.split("\t");
        List<String> row = new ArrayList<>();
        for(int i=0; i<datas.length; i++){
            String data = datas[i];
            row.add(data);
        }
        dataTemplate.getDatas().add(row);
    }

}
